package com.example.administrator.text;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.AppCompatCheckBox;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import util.BReceiverUtil.SMSBroadcastReceiver;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetUtils;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import view.diaLogView.CrowdRetunDialog;
import view.diaLogView.PhoneMessageDialog;
import view.diaLogView.UploadDialog;

/**
 * 修改信息页
 */
public class ModifyInformationActivity extends BaseActivity {
    private String mType,mToken,mID,mUrl,mValue;
    private String mStringPhone,mStringPassword;
    private String mStringContent;
    public static String PWD = "pwd";             //密码
    public static String NICKNAME = "nickname";  //昵称
    public static String NIUNUM = "niuNum";     //牛号
    public static String SEX = "sex";          //性别
    public static String SELFSOM = "selfdom"; //个性
    public static String WEHEAD= "weHead";   //头像地址
    public static String PHONE = "phone";   //手机号
    public boolean mJuderMessage = true;
    private boolean mModif_nan,mModif_nV = true;
    private UploadDialog mUploadDialog;
    private SMSBroadcastReceiver mSmsBroadcastReceiver;

    @Bind(R.id.modifypassword_frame)         FrameLayout mFrameLayout;
    @Bind(R.id.relati_weinformation)         RelativeLayout mRelativeLayout;
    @Bind(R.id.linear_modif)                 LinearLayout mLayout;
    @Bind(R.id.linear_modif_sex)             LinearLayout mLayoutSex;
    @Bind(R.id.text_modify_name)             TextView mTVName;
    @Bind(R.id.text_modify_verification)     TextView mTVVerification;
    @Bind(R.id.edittext_weinformation)       EditText mEditText;
    @Bind(R.id.edit_modify_phone)            EditText mETPhone;
    @Bind(R.id.edit_modify_verification)     EditText mETVerification;
    @Bind(R.id.checkbox_modify_nan)          AppCompatCheckBox mBoxNan;
    @Bind(R.id.checkbox_modify_nv)           AppCompatCheckBox mBoxNv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modifypassword);
        ButterKnife.bind(this);
        init();

    }

    private void init() {
        mType = getIntent().getStringExtra("type");
        HomeUtil.getHemeUtilNew().getStatusBar(this,mFrameLayout);
        mToken = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mTokenDB,"");
        mID = (String) SharedPreferencesUtils.getParam(this,HomeUtil.mUseridDB,"");
        if(mType.equals(PWD)){
            mTVName.setText("设置密码");
            mRelativeLayout.setVisibility(View.VISIBLE);
            mEditText.setHint("请输入您要修改的密码(6到12位的数字或字母)");
            mLayout.setVisibility(View.GONE);
            mLayoutSex.setVisibility(View.GONE);
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }else if(mType.equals(NICKNAME)){
            mTVName.setText("设置昵称");
            mRelativeLayout.setVisibility(View.VISIBLE);
            mEditText.setHint("请输入您要修改的昵称");
            mLayout.setVisibility(View.GONE);
            mLayoutSex.setVisibility(View.GONE);
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }else if(mType.equals(SEX)){
            mTVName.setText("设置性别");
            mRelativeLayout.setVisibility(View.GONE);
            mEditText.setHint("请输入您要修改的性别");
            mLayout.setVisibility(View.GONE);
            mLayoutSex.setVisibility(View.VISIBLE);
        }else if(mType.equals(SELFSOM)){
            mTVName.setText("设置签名");
            mRelativeLayout.setVisibility(View.VISIBLE);
            mEditText.setHint("请输入您要修改的签名");
            mLayout.setVisibility(View.GONE);
            mLayoutSex.setVisibility(View.GONE);
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }else if(mType.equals(PHONE)){
            mTVName.setText("设置手机号");
            mRelativeLayout.setVisibility(View.GONE);
            mLayout.setVisibility(View.VISIBLE);
            mLayoutSex.setVisibility(View.GONE);
            mEditText.setHint("请输入您要修改的手机号");
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }

        mETPhone.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    mTVVerification.setBackground(getResources().getDrawable(R.color.Land_true));
                    mTVVerification.setTextColor(getResources().getColor(R.color.bg_color));
                    mStringPhone = s.toString();
                } else if (s.length() <11) {
                    mStringPhone = s.toString();
                    mTVVerification.setTextColor(getResources().getColor(R.color.Land_true));
                    mTVVerification.setBackground(getResources().getDrawable(R.drawable.register_two_ba));
                }
            }

            @Override public void afterTextChanged(Editable s) {

            }
        });

        mBoxNan.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                   if(isChecked){
                       mBoxNv.setChecked(false);
                   }
            }
        });

        mBoxNv.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mBoxNan.setChecked(false);
                }
            }
        });
    }

    /**
     * 返回
     */
    @OnClick(R.id.image_modifypassword)
    void Return(){
        finish();
    }

    /**
     * 验证码
     */
    @OnClick(R.id.text_modify_verification)
    void modifyVerification(){

        if (StringUtil.getStringUtilNew().isMobile(mStringPhone)) {
            if (NetUtils.getInstance(this).checkNetWork()) {
                if (mJuderMessage) {
                    HomeUtil.getHemeUtilNew().getMessage(this,mETVerification,mSmsBroadcastReceiver);
                    mMap = new HashMap<>();
                    mMap.put("phone", mStringPhone);
                    mMap.put("authCodeType",0);
                    String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
                    long time = StringUtil.getStringUtilNew().getTimeCurrent();
                    String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngPhoneVerification,stringJson,"null","0",time);
                    Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,"null","0",Url.mStirngPhoneVerification,stirngSign,time);
                    HomeUtil.getHemeUtilNew().obtainVerification(this,map1,MyApplication.getApp().getFWQString(),mTVVerification,0,0);
                    mJuderMessage = false;
                } else {
                    PhoneMessageDialog phoneMessageDialog = new PhoneMessageDialog(this,mStringPhone,MyApplication.getApp().getFWQString(),mETVerification, mTVVerification);
                    phoneMessageDialog.show();
                }

            } else {
                super.getToast(getString(R.string.no_network));
            }

        } else {
            super.getToast(getString(R.string.no_phone));
        }
    }

    /**
     * 完成
     */
    @OnClick(R.id.text_modifypassword)
    void ok(){

         if(!mType.equals(PHONE)){
             mStringContent = mEditText.getText().toString().trim();
             HashMap<String,Object> hashMap = new HashMap<>();
             hashMap.put("userid",mID);
             hashMap.put("type",mType);
             if(mType.equals(SEX)){
                 if(mBoxNan.isChecked()){
                     mStringContent = "1";
                 }
                 if(mBoxNv.isChecked()){
                     mStringContent = "2";
                 }
                 if(mStringContent.equals("")){
                     getToast("请选择性别");
                     return;
                 }
             }

             if(mType.equals(PWD)){
                 if(StringUtil.getStringUtilNew().getStatePassword(mStringContent)){
                     mStringContent = StringUtil.getStringUtilNew().getMD5String(mStringContent);
                 }else {
                     getToast("请输入符合规定的密码");
                     return;
                 }
             }

             if(mStringContent.equals("")){
                 getToast("修改的内容不能为空");
                 return;
             }

             hashMap.put("content",mStringContent);
             String stringJson = StringUtil.getStringUtilNew().hashMapToJson(hashMap);
             long time = StringUtil.getStringUtilNew().getTimeCurrent();
             String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngUserContent_updateContent,stringJson,mToken,mID,time);
             Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mID,Url.mStirngUserContent_updateContent,stirngSign,time);
             if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
                 mUrl = Url.getUrlNew().getAppIP();
             }else {
                 mUrl = MyApplication.getApp().getFWQString();
             }

             mUploadDialog = new UploadDialog(this,"保存中");
             mUploadDialog.show();
             getLogger().info("ok()--->修改个人信息--fwq"+mUrl+"stirngSign--"+stirngSign+"....stringJson...."+stringJson);
             GreenTreeNetworkUtil.getInstance().doPost(this,mUrl,1,map,new RequestDataCallback() {
                 @Override public void onSuccess(String response) {
                     try {
                         getLogger().info("ok()--->onSuccess()--String"+response);
                         JSONObject jsonObject = new JSONObject(response);
                         LogUtil.eE("",response);
                         mUploadDialog.dismiss();
                         if (jsonObject.getInt("code") == 1) {
                             setInformation(mStringContent);
                             if(mType.equals(SEX)){
                                 if(mStringContent.equals("1")){
                                     mStringContent = "男";
                                 }else if(mStringContent.equals("2")){
                                     mStringContent = "女";
                                 }
                             }
                             Intent intent = new Intent();
                             intent.putExtra("type",mType);
                             intent.putExtra("content",mStringContent);
                             setResult(RESULT_OK, intent);
                             finish();
                         } else if(jsonObject.getInt("code") == -2){
                             CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(ModifyInformationActivity.this);
                             crowdRetunDialog.show();
                         }
                         else {getToast(getString(R.string.FWQ));}

                     } catch (JSONException e) {e.printStackTrace();}
                 }

                 @Override public void onFailure(Throwable error) {
                     mUploadDialog.dismiss();
                     StringUtil.getStringUtilNew().getExceptionCode(ModifyInformationActivity.this,error.toString());
                 }});
         }else {
             setPhone();
         }
    }

    /**
     * 设置手机号
     */
    private void setPhone() {
        final String phone = mETPhone.getText().toString().trim();
        final String verification = mETVerification.getText().toString().trim();
        if(getEntryObtain()){
            HashMap<String,Object> hashMap = new HashMap<>();
            hashMap.put("userid",mID);
            hashMap.put("phone",phone);
            hashMap.put("authcode",verification);
            String stringJson = StringUtil.getStringUtilNew().hashMapToJson(hashMap);
            long time = StringUtil.getStringUtilNew().getTimeCurrent();
            String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngUserContent_updatePhone,stringJson,mToken,mID,time);
            Map map = StringUtil.getStringUtilNew().getMapNew(this,stringJson,mToken,mID,Url.mStirngUserContent_updatePhone,stirngSign,time);
            if(NetUtils.getInstance(this).getNetWorkTeyt() == 0){
                mUrl = Url.getUrlNew().getAppIP();
            }else {
                mUrl = MyApplication.getApp().getFWQString();
            }
            getLogger().info("setPhone()--->修改手机号码--fwq"+mUrl+"stirngSign--"+stirngSign);
            GreenTreeNetworkUtil.getInstance().doPost(this,mUrl,1,map,new RequestDataCallback() {
                @Override public void onSuccess(String response) {
                    try {
                        getLogger().info("setPhone()--->onSuccess--String"+response);
                        JSONObject jsonObject = new JSONObject(response);
                        LogUtil.eE("",response);
                        if (jsonObject.getInt("code") == 1) {
                            Intent intent = new Intent();
                            intent.putExtra("type",mType);
                            intent.putExtra("content",phone);
                            setResult(RESULT_OK, intent);
                            finish();
                        } else if(jsonObject.getInt("code") == -2){
                            CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(ModifyInformationActivity.this);
                            crowdRetunDialog.show();
                        }
                        else {getToast(getString(R.string.FWQ));}

                    } catch (JSONException e) {e.printStackTrace();}
                }

                @Override public void onFailure(Throwable error) {
                    StringUtil.getStringUtilNew().getExceptionCode(ModifyInformationActivity.this,error.toString());
                }});
        }
    }

    /**
     * 男
     */
    @OnClick(R.id.linear_modif_nan)
    void modif_nan(){
        if(mModif_nan){
            mModif_nan = false;
            mBoxNan.setChecked(true);
            mBoxNv.setChecked(false);
            mModif_nV = true;

        }else {
            mModif_nan = true;
            mBoxNan.setChecked(false);
        }

    }

    /**
     * 成功后保障在本地
     */
     private void setInformation(String string){
         if(mType.equals(PWD)){
             SharedPreferencesUtils.setParam(this,ModifyInformationActivity.PWD,1);
         }else if(mType.equals(NICKNAME)){
             SharedPreferencesUtils.setParam(this,ModifyInformationActivity.NICKNAME,string);
         }else if(mType.equals(SEX)){
             LogUtil.eE("",string+"");
             if(string.equals("1")){
                 SharedPreferencesUtils.setParam(this,ModifyInformationActivity.SEX,1);
             }else if(string.equals("2")){
                 SharedPreferencesUtils.setParam(this,ModifyInformationActivity.SEX,2);
             }
         }else if(mType.equals(SELFSOM)){
             SharedPreferencesUtils.setParam(this,ModifyInformationActivity.SELFSOM,string);
         }else if(mType.equals(PHONE)){
             SharedPreferencesUtils.setParam(this,ModifyInformationActivity.PHONE,string);
         }
     }

    /**
     * 女
     */
    @OnClick(R.id.linear_modif_nv)
    void modif_nv(){
        if(mModif_nV){
            mModif_nV = false;
            mBoxNv.setChecked(true);
            mBoxNan.setChecked(false);
            mModif_nan = true;

        }else {
            mModif_nV = true;
            mBoxNv.setChecked(false);

        }
    }

    /**
     * 获取和验证登录信息
     */
    private boolean getEntryObtain() {

        mStringPhone = mETPhone.getText().toString().trim();
        mStringPassword = mETVerification.getText().toString().trim();

        if (!StringUtil.getStringUtilNew().isMobile(mStringPhone)) {
            super.getToast("手机号不正确");
            return false;
        }
        if (!StringUtil.getStringUtilNew().getStatePassword(mStringPassword)) {
            super.getToast("密码或验证码不正确");
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mUploadDialog !=null){
            mUploadDialog.dismiss();
        }

        if(mSmsBroadcastReceiver !=null){
            unregisterReceiver(mSmsBroadcastReceiver);
        }
    }
}
